#!/usr/bin/env python
# -*- coding: utf-8 -*-
#  PushManager.py
#  description

#  Created by zhouzongli633 on 2020/8/31 3:01 下午.
#  Copyright ©Intellectus All rights reserved.
import datetime

import firebase_admin
from firebase_admin import messaging, credentials

from Common.apns import APNs, Payload
from NICU2HOME.settings import APN_CER_PATH, APN_KEY_PATH, SERVICE_ACCOUNT_KEY

apn = APNs(use_sandbox=True, cert_file=APN_CER_PATH, key_file=APN_KEY_PATH)
cred = credentials.Certificate(SERVICE_ACCOUNT_KEY)
fcm = firebase_admin.initialize_app(cred)


class PushManager(object):
    def __init__(self):
        self.apn = apn
        self.fcm = fcm

    def push_message(self, user_agent, token, message):
        if user_agent.lower() == 'ios':
            payload = Payload(alert=message, sound=None, badge=1, mutable_content=True, content_available=True)
            self.apn.gateway_server.send_notification(token, payload)
        elif user_agent.lower() == 'android':
            message = messaging.Message(
                data={'score': '850', 'time': '2:45', },
                token=token,
            )
            response = messaging.send(message)
            # Response is a message ID string.
            print('Successfully sent message:', response)

    def push_message_with_user(self, user, message):
        user_token_p = user.push_notifications
        token = user_token_p.token
        user_agent = user_token_p.user_agent
        if user_agent.lower() == 'ios':
            payload = Payload(alert=message, sound=None, badge=2, mutable_content=True, content_available=True)
            self.apn.gateway_server.send_notification(token, payload)
        elif user_agent.lower() == 'android':
            message = messaging.Message(
                data={'score': '850', 'time': '2:45', },
                token=token,
            )
            response = messaging.send(message)
            # Response is a message ID string.
            print('Successfully sent message:', response)

    def get_apns_feedback(self):
        feedbacks = self.apn.feedback_server.items()
        print(f"feedbacks:{feedbacks}")
        for (token_hex, fail_time) in feedbacks:
            # todo - check invalid token, update database
            print(token_hex)


if __name__ == "__main__":
    noti_msg = "ding dong~"
    # token_hex = "18ac9f7e55d2c8a3f2715e1249cc2eaea1e402ea8413ef253b73b00616c64fb7"  # Alex
    # token_hex = "d6a60db238ccec89b7232639d40b9f909ebcb66a4fb28b8a25f2111abf0c2f4f"  # label
    token_hex = "2f6afc3fc1f687d9f06d4be396d7f7a90d9bf8e24d166bb4b2768ef5c09d69e6"  # ben

    pusher = PushManager()
    pusher.push_message('ios', token_hex, noti_msg)
